package vip.xiaonuo.biz.websocket;

import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class WebSocketServerHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    private static List<Channel>  ctxList = new ArrayList<>();
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame msg) {
        if (msg instanceof TextWebSocketFrame) {
            String message = ((TextWebSocketFrame) msg).text();
        }
    }
    //客户端建立连接
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        ctxList.add(ctx.channel());
        System.out.println(ctx.channel().remoteAddress()+"上线了!");
    }

    //关闭连接
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+"断开连接");
        ctxList.remove(ctx.channel());
    }


    public static void SendMessage(String msg) {
        for (Channel channel : ctxList) {
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(msg)));
        }

    }
}